package cn.itrip.utlis;

import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.beans.vo.TokenVO;
import com.alibaba.fastjson.JSONObject;

public class TokenUtil {
    private RedisAPI redisAPI;

    public void setRedisAPI(RedisAPI redisAPI) {
        this.redisAPI = redisAPI;
    }

    public TokenVO createToken(ItripUser user, String userAgent) {
        StringBuffer buffer = new StringBuffer();
        if(UserAgentUtil.isPc(userAgent)) {
            buffer.append("token:PC-");
        }else {
            buffer.append("token:mobile-");
        }
        buffer.append(MD5.md5(user.getUserCode()));
        buffer.append("-").append(user.getId());
        buffer.append("-").append(System.currentTimeMillis());
        buffer.append("-").append(MD5.md5(userAgent).substring(0,6));
        TokenVO tokenVo = new TokenVO();
        tokenVo.setToken(buffer.toString());
        tokenVo.setGetTime(System.currentTimeMillis());
         if(UserAgentUtil.isPc(userAgent)) {
             tokenVo.setExpTime(System.currentTimeMillis() + 7200000);
             redisAPI.setex(tokenVo.getToken(),7200, JSONObject.toJSONString(user));
        }else {
            redisAPI.set(tokenVo.getToken(), JSONObject.toJSONString(user));
        }
        return tokenVo;
    }


    public ItripUser getUser(String token) {
        String userInfo = redisAPI.get(token);
        if (userInfo != null) {
            return JSONObject.parseObject(userInfo, ItripUser.class);
        }
        return null;
    }
}
